﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Net;
using System.IO;
using Site_Extractor;
using Common;
using Site_Extractor_GUI.Properties;
using StandardAnalyzer = Lucene.Net.Analysis.Standard.StandardAnalyzer;
using Document = Lucene.Net.Documents.Document;
using IndexReader = Lucene.Net.Index.IndexReader;
using IndexWriter = Lucene.Net.Index.IndexWriter;
using Term = Lucene.Net.Index.Term;
using TermEnum = Lucene.Net.Index.TermEnum;
using Lucene.Net.Search;
using Lucene.Net.Analysis;
using System.Collections;

namespace Site_Extractor_GUI
{
	public partial class SiteExtractorGUI : Form
	{
        Indexer indexer = new Indexer(Properties.Settings.Default.ConnectionString, "");
		List<Site> _sites;
		SplitterPanel _controlPanel;
        const string indexDir = @"D:\Documents and Settings\Roey Lehman\Desktop\Incubating-Apache-Lucene.Net-2.0-004-11Mar07.src\src\Demo\IndexHtml";

        IndexWriter IndexWriter = new IndexWriter(indexDir, new SimpleAnalyzer(), true);
		bool _working = false;
        string _RssDefaultFeed = "http://www.haaretz.co.il/feed/newsRss.xml";
		public SiteExtractorGUI()
		{
			InitializeComponent();
			rssTextBox.Text = _RssDefaultFeed;
			_controlPanel = splitContainer1.Panel1;

			var sites = XmlClassHandler<Site[]>.Load(Settings.Default.PathToSitesXML);
			_sites = new List<Site>(sites);	

		}

		private void rssTextBox_TextChanged(object sender, EventArgs e)
		{
			rssButton.Enabled=rssTextBox.Text!=string.Empty && !_working;
		}

		private void rssButton_Click(object sender, EventArgs e)
		{
			_working = true;
			_controlPanel.Enabled = false;
			BackgroundWorker rssWorker = new BackgroundWorker();
			rssWorker.WorkerReportsProgress = false;
			rssWorker.WorkerSupportsCancellation = false;
			rssWorker.DoWork += new DoWorkEventHandler(rssWorker_DoWork);
			rssWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(rssWorker_RunWorkerCompleted);
			rssWorker.RunWorkerAsync(rssTextBox.Text);
		}

		void PlaceFeeds(ListBox box, List<RssLink> items) 
		{
       

			box.Items.Clear();
            foreach (RssLink lnk in items)
            {
                box.Items.Add(lnk);
                Story story = null; //Index the links in the catalog!
                Uri uri = new Uri(lnk.Link);



                foreach (Site site in _sites)
                {
                    if (!site.InDomain(uri)) continue;
                    story = SiteExtractor.ExtractStory(site, uri);
                    Document Document = new Document();
                    Document.Add(new Lucene.Net.Documents.Field("Title", story.Title,
                        Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.TOKENIZED));
                    Document.Add(new Lucene.Net.Documents.Field("Summary", story.Summary,  
                        Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.TOKENIZED));
                    Document.Add(new Lucene.Net.Documents.Field("Text", "זה סתם חרא!!!",  
                        Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.TOKENIZED));
 
                    IndexWriter.AddDocument(Document);
                   
            

                    indexer.indexRssStory(site, lnk);
                }
               
            }
            IndexWriter.Optimize();
           
		}

		void rssWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			Invoke(new Action<ListBox, List<RssLink>>(PlaceFeeds), rssListBox, e.Result as List<RssLink>);

			_controlPanel.Enabled = true;
			_working=false;
		}

		void rssWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			//e.Result = RssLink.GetLinks(e.Argument as string);
		}



		private void rssListBox_SelectedValueChanged(object sender, EventArgs e)
		{
			if (rssListBox.SelectedItem == null) return;
			try
			{
				if (rssListBox.SelectedItem is RssLink)
				{
					RssLink lnk = rssListBox.SelectedItem as RssLink;
					linkTextBox.Text = lnk.Link;
					getStoryButton.Enabled = false;
				}
				else if (rssListBox.SelectedItem is Common.Document)
				{
					Common.Document doc = rssListBox.SelectedItem as Common.Document;
					getStoryButton.Enabled = false;
					//titleTextBox.Text = doc.Title;
					//summaryTextBox.Text = doc.Summary;
					//storyTextBox.Text = doc.Text;
					dateTimeTextBox.Text = doc.DateTime.ToString();					
				}
			}
			catch { getStoryButton.Enabled = false; }
		}

		private void getStoryButton_Click(object sender, EventArgs e)
		{
			BackgroundWorker storyWorker = new BackgroundWorker();
			storyWorker.WorkerReportsProgress = false;
			storyWorker.WorkerSupportsCancellation = false;
			storyWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(storyWorker_RunWorkerCompleted);
			storyWorker.DoWork += new DoWorkEventHandler(storyWorker_DoWork);
			storyWorker.RunWorkerAsync(linkTextBox.Text); // link
			_controlPanel.Enabled = false;
		}

		void storyWorker_DoWork(object sender, DoWorkEventArgs e)
		{
			/*Story story = null;
			YnetExtractor y = new YnetExtractor();
			HaaretzExtractor h = new HaaretzExtractor();
			var uri = new Uri(e.Argument as string);
			if (uri.Host == y.ExtractorDomain()) story = y.GetStory(uri);
			else if (uri.Host == h.ExtractorDomain()) story = h.GetStory(uri);*/
			//e.Result = story;

			Story story = null;
			Uri uri=new Uri(e.Argument as string);
			

			foreach (Site site in _sites)
			{
				if (!site.InDomain(uri)) continue;
				story = SiteExtractor.ExtractStory(site, uri);
			}
			e.Result = story;
		}

		void storyWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			// enable button
			// populate fields
			// reset progress
			_controlPanel.Enabled = true;
			if (e.Result == null) return;
			Story story = e.Result as Story;
			titleTextBox.Text = story.Title;
			summaryTextBox.Text = story.Summary;
			storyTextBox.Text = story.Text;
            dateTimeTextBox.Text = story.date;
		}

		private void linkTextBox_TextChanged(object sender, EventArgs e)
		{
			if (linkTextBox.Text == string.Empty) return;
			if (_working) return;
			getStoryButton.Enabled = true;
		}

        private void button1_Click(object sender, EventArgs e)
        {
            /*Lucene.Net.Search.IndexSearcher searcher = new Lucene.Net.Search.IndexSearcher(indexDir);


            Lucene.Net.QueryParsers.QueryParser queryParser = new 
            Lucene.Net.QueryParsers.QueryParser("Text", new SimpleAnalyzer());
            queryParser.SetPhraseSlop(1);
            
            //parse the query string into a Query object
            Lucene.Net.Search.Query
            query = queryParser.Parse(linkTextBox.Text);
            
            FuzzyQuery FuzzyQuery = new FuzzyQuery(new Term("Text",linkTextBox.Text), 0.6f);
 
            Lucene.Net.Search.Hits hits = searcher.Search(query);

            //iterate over the results.
            for (int i = 0; i < hits.Length(); i++)
            {
                Document doc = hits.Doc(i);
                string contentValue = doc.Get("Title");

                rssListBox.Items.Add(contentValue);

            }*/
            rssListBox.Items.Clear();
            Searcher.Searcher searcher = new Searcher.Searcher();

           foreach (Common.Document doc in  searcher.DoSearch(linkTextBox.Text, indexer.Catalo))
            {

                rssListBox.Items.Add(doc);
            }
            //IndexWriter.Close();
        }
	}
}
